package cn.easier.activity.console.utils;

import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

	private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
	private static final SimpleDateFormat DEFAULT_FORMATTER = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
	public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_YEAR = "yyyy";
	public static final String FORMAT_YEAR_MONTH = "yyyy-MM";
	public static final String FORMAT_YEAR_MONTH_DAY = "yyyy-MM-dd";
	public static final String FORMAT_HOUR_MINUTE_SECOND = "HH:mm:ss";
	public static final String CN_DATE_FORMAT = "yyyy年MM月dd日";

	public static final String PURE_FORMATE_YEAR = "yyyy";
	public static final String PURE_FORMATE_MONTH = "yyyyMM";
	public static final String PURE_FORMATE_DAY = "yyyyMMdd";

	/**
	 * 将日期格式化为字符串
	 * 
	 * @param date
	 *            日期
	 * @param pattern
	 *            格式
	 * @return 格式化后的日期串
	 */
	public static String date2Str(Date date, String pattern) {
		if (null == date) {
			return null;
		}
		if (null == pattern) {
			pattern = DEFAULT_DATE_FORMAT;
		}
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.format(date);
	}

	/**
	 * 按指定格式将字符串转换为日期
	 * 
	 * @param dateStr
	 *            日期串
	 * @param pattern
	 *            格式
	 * @return 日期
	 * @throws Exception
	 *             异常
	 */
	public static Date str2Date(String dateStr, String pattern)
			throws Exception {
		if (null == dateStr) {
			return null;
		}
		if (null == pattern) {
			pattern = DEFAULT_DATE_FORMAT;
		}
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.parse(dateStr);
	}

	public static Date parse(String date) {
		return parse(date, null);
	}

	/**
	 * 将字符串转换为Date类型
	 *
	 * @param date    字符串类型
	 * @param pattern 格式，为空则默认 yyyy-MM-dd HH:mm:ss
	 * @return 日期类型
	 */
	public static Date parse(String date, String pattern) {
		if (StringUtils.isBlank(date)) {
			return null;
		}
		Date d = null;
		if (StringUtils.isBlank(pattern)) {
			try {
				d = DEFAULT_FORMATTER.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			try {
				d = new SimpleDateFormat(pattern).parse(date);
			} catch (ParseException pe) {
				pe.printStackTrace();
			}
		}
		return d;
	}

}
